package cn.itcast.shiro;

import cn.itcast.domain.Module;
import cn.itcast.domain.User;
import cn.itcast.service.module.ModuleService;
import cn.itcast.service.user.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class AuthRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    private ModuleService moduleService;
    @Override /*做授权*/
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //1.获取安全数据中的user对象
        User user = (User)principalCollection.getPrimaryPrincipal();
        //2.调用moduleService查询当前用户所有的操作菜单权限
        List<Module> menus = moduleService.findMenus(user);
        //3.返回参数：是权限集合
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        Set<String> set=new HashSet<>();
        for (Module menu : menus) {
            set.add(menu.getName());
        }
        System.out.println(set);
        simpleAuthorizationInfo.setStringPermissions(set);
        return simpleAuthorizationInfo;
    }

    @Override/*做认证有关的方法*/
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
      UsernamePasswordToken uPasswordToken=(UsernamePasswordToken)authenticationToken;
      /*获取前端的用户名*/
        String username = uPasswordToken.getUsername();
        // 根据email获取到数据库的安全数据（User对象）
        User user = userService.findByUserName(username);
        if (user==null){
            /*返回null 给shior会抛出异常代表meichadao*/
            return null;
        }
        //user不为空的情况下调用密码比较器
        //给密码比较器传递的参数
        //参数1：数据库查询出来的安全数据对象
        //参数2：数据库安全数据对象的密码证书
        //参数3：当前AuthRealm的名称
        return new SimpleAuthenticationInfo(user,user.getPassword(),this.getName());
    }
}
